<script>
	export default {
		onLaunch() {
			// #ifdef APP-PLUS
			this.checkVersion();
			// #endif
		},
		onShow() {
			console.log("App Show");
		},
		onHide() {
			console.log("App Hide");
		},
		methods: {
			async checkVersion() {
				const { data, msg: title, code } = await this.$request.get("/Home/Login/get_version", {
					platform: uni.getSystemInfoSync().platform,
					version: plus.runtime.version,
				});

				if (code !== 302) return;

				const [showModalFail, showModalRes] = await uni.showModal({
					title,
					content: data.description,
					showCancel: Boolean(+data.forceUpdate),
				});

				if (showModalFail || !showModalRes.cancel) return;

				if (uni.getSystemInfoSync().platform == "ios") {
					plus.runtime.openURL(data.upgrade_url);
					return;
				}

				const showLoading = plus.nativeUI.showWaiting("开始下载...");

				const downloadTask = uni.downloadFile({
					url: data.upgrade_url,
					success: ({ tempFilePath }) => {
						showLoading.setTitle("正在安装...");

						plus.runtime.install(
							tempFilePath,
							{},
							(e) => {
								plus.nativeUI.closeWaiting();
								uni.showModal({
									title: "更新完成",
									content: "新版本需要重启APP",
									confirmText: "立即重启",
									showCancel: false,
									success: plus.runtime.restart,
								});
							},
							(error) => {
								plus.nativeUI.closeWaiting();
								uni.showToast({ title: "安装失败", icon: "none" });
							}
						);
					},
					fail() {
						uni.showToast({ title: "下载失败", icon: "none" });
					},
				});

				downloadTask.onProgressUpdate(
					({ progress, totalBytesWritten, totalBytesExpectedToWrite }) =>
						showLoading.setTitle(
							`正在下载(${(totalBytesWritten / 1024 ** 2).toFixed(2)}MB/${(
								totalBytesExpectedToWrite /
								1024 ** 2
							).toFixed(2)}MB)	${progress}%`
						)
				);
			},
		},
	};
</script>

<style>
	/*每个页面公共css */
	page {
		background-color: #f7f7f7;
	}
</style>
